<template>
	<view class="user-card-holder">
		<ShareCanvas ref="shareCanvas" />
		<view class="search-bar">
			<view class="search">
				<input focus placeholder="输入姓名查询" @input="handleOnSearch" />
				<image src="/static/search.svg" style="width: 40rpx;height: 40rpx;"></image>
			</view>
		</view>
		<template v-for="i in users" :key="i.id">
			<ECard class="ecard" :user-info="i" :setting="getItemSetting(i.id)" :hide-actions="true" :hide-share-action="true"
				:show-tool-bar="true" />
		</template>
		<Empty class v-if="!users.length" text="暂无名片" />
	</view>
</template>

<script setup>
	import ShareCanvas from '../../components/share.vue'
	import ECard from '../../components/ecard.vue'
	import Empty from '../../components/empty.vue';
	import { onShow, onShareAppMessage } from '@dcloudio/uni-app'
	import { computed, ref } from 'vue';
	import { getECardUserInfoList, getECardUsers } from '../../request/api/ecard';
	import { storeToRefs } from 'pinia';
	import { useUserStore } from '../../store/user';
	import { useECardStore } from '../../store/ecard';
	import { buildShareObject } from '../../utils/share';

	// data
	const shareCanvas = ref() // 分享图片
	const { info: user } = storeToRefs(useUserStore())
	const userInfos = ref([]) // 用户信息列表
	const search = ref('') // 查询关键字
	const users = computed(() => {
		// 排除本人
		const data = userInfos.value.filter(u => u.id !== user.value.id)
		if (!search.value) return data
		// 检索姓名
		return data.filter(u => u.nickname.indexOf(search.value) !== -1)
	})
	const { settings, active } = storeToRefs(useECardStore()) // 配置项
	const setting = computed(() => { // 当前配置项
		return settings.value[active.value] || {}
	})
	const ecardUsers = ref([]) // 配置的用户信息

	// methods
	const handleOnSearch = (e) => {
		const { value } = e.detail
		search.value = value
	}
	const loadData = () => {
		if (!setting.value.id) return Promise.reject({ code: -1, message: '参数错误' })
		return getECardUserInfoList({}, setting.value.id, 1, 1000000).then(({ records = [] }) => {
			userInfos.value = records
			return Promise.resolve(userInfos.value)
		}).catch(({ code = -1, message = '' }) => {
			return Promise.reject({ code, message })
		})
	}
	/**
	 * 卡片项的user id
	 */
	const loadECardUsers = () => {
		if (!setting.value.id) return Promise.reject({ code: -1, message: '参数错误' })
		return getECardUsers(setting.value.id).then(data => {
			ecardUsers.value = data
			return Promise.resolve(ecardUsers.value)
		}).catch(({ code = -1, message = '' }) => {
			return Promise.reject({ code, message })
		})
	}
	/**
	 * 获取卡片的配置
	 */
	const getItemSetting = (userId) => {
		const s = { ...setting.value }
		const ecardUser = ecardUsers.value.filter(u => u.uid === userId)[0] || {}
		s.currentCardUser = ecardUser
		return s
	}

	// lifecircle
	onShow(() => {
		uni.showLoading({ title: '加载中……', })
		Promise.all([loadData(), loadECardUsers()]).catch(() => {
			uni.showToast({
				title: '数据加载失败',
				icon: 'error'
			})
		}).finally(() => {
			uni.hideLoading()
		})
	})

	onShareAppMessage(async (res) => {
		if (res.from === 'button') {
			uni.showLoading({ title: '请稍候……' })
			try {
				const user = res.target.dataset.user || {}
				const obj = buildShareObject(getItemSetting(user.id), user)
				const imageUrl = await shareCanvas.value.buildPreviewImage(obj)
				return {
					title: `${user.nickname}的名片`,
					path: `/pages/share/share?uid=${user.id}&sid=${setting.value.id}`,
					imageUrl
				}
			} finally {
				uni.hideLoading()
			}
		} else {
			return {
				title: '中路建设（云南）有限公司',
				path: '/pages/index/index',
				imageUrl: '/static/logo.png'
			}
		}
	})
</script>

<style lang="scss" scoped>
	.user-card-holder {
		display: flex;
		flex-direction: column;
		gap: 40rpx;

		&>.ecard:last-child {
			margin-bottom: 40rpx;
		}
	}

	.search-bar {
		padding: 40rpx;
		padding-bottom: 0;

		&>.search {
			display: flex;
			align-items: center;
			border: 1px solid #1AAD19;
			padding: 20rpx;
			border-radius: 20rpx;

			&>input {
				flex: 1;
			}
		}
	}
</style>